<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <input 
        class="search-input" 
        placeholder="搜索音乐" 
        v-model="searchKeyword"
        @confirm="handleSearch"
      />
    </view>

    <!-- 轮播图 -->
    <view class="banner-section">
      <swiper 
        class="banner-swiper" 
        :indicator-dots="true" 
        :autoplay="true" 
        :interval="3000" 
        :duration="500"
        circular
      >
        <swiper-item v-for="(banner, index) in banners" :key="index">
          <image 
            class="banner-image" 
            :src="banner.image_url" 
            mode="aspectFill"
            @click="handleBannerClick(banner)"
          />
        </swiper-item>
      </swiper>
    </view>

    <!-- 推荐歌曲 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">推荐歌曲</text>
        <text class="section-more" @click="goToMore('recommended')">更多</text>
      </view>
      <view class="song-list-vertical">
        <view class="song-item-vertical" v-for="(song, index) in uniqueRecommendedSongs" :key="song.song_id" @click="playSong(song, index)">
          <image class="song-cover-vertical" :src="song.cover_image_url" mode="aspectFill" />
          <view class="song-info-vertical">
            <text class="song-name-vertical">{{ song.name }}</text>
            <text class="song-artist-vertical">{{ song.artist_name }}</text>
          </view>
          <view class="song-play-btn">
            <text class="play-icon">▶️</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 热门歌曲 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">热门歌曲</text>
        <text class="section-more" @click="goToMore('hot')">更多</text>
      </view>
      <view class="song-list-vertical">
        <view class="song-item-vertical" v-for="(song, index) in uniqueHotSongs" :key="song.song_id" @click="playSong(song, index)">
          <image class="song-cover-vertical" :src="song.cover_image_url" mode="aspectFill" />
          <view class="song-info-vertical">
            <text class="song-name-vertical">{{ song.name }}</text>
            <text class="song-artist-vertical">{{ song.artist_name }}</text>
          </view>
          <view class="song-play-btn">
            <text class="play-icon">▶️</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部播放器 -->
    <view class="mini-player" v-if="currentSong" @click="goToPlayer">
      <image class="mini-player-cover" :src="currentSong.cover_image_url" mode="aspectFill" />
      <view class="mini-player-info">
        <text class="mini-player-name">{{ currentSong.name }}</text>
        <text class="mini-player-artist">{{ currentSong.artist_name }}</text>
      </view>
      <view class="mini-player-controls">
        <text class="control-btn" @click.stop="togglePlay">
          {{ isPlaying ? '⏸️' : '▶️' }}
        </text>
        <text class="control-btn" @click.stop="nextSong">⏭️</text>
      </view>
    </view>
  </view>
</template>

<script>
// 内联API配置以避免模块导入问题
const BASE_URL = 'http://localhost:3000/api'

function request(options) {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    if (token) {
      options.header = {
        ...options.header,
        'Authorization': `Bearer ${token}`
      }
    }

    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 导入音乐播放器
import musicPlayer from '/utils/musicPlayer.js'

const api = {
  music: {
    getBanners() {
      return request({
        url: '/music/banners',
        method: 'GET'
      })
    },
    getRecommended() {
      return request({
        url: '/music/recommended',
        method: 'GET'
      })
    },
    getHot() {
      return request({
        url: '/music/hot',
        method: 'GET'
      })
    },
    // 添加获取歌曲详情的API
    getSongDetail(songId) {
      return request({
        url: `/music/song/${songId}`,
        method: 'GET'
      })
    }
  }
}

export default {
  data() {
    return {
      banners: [],
      recommendedSongs: [],
      hotSongs: [],
      searchKeyword: '',
      currentSong: null,
      isPlaying: false
    }
  },

  computed: {
    // 去重后的推荐歌曲（只显示前3首）
    uniqueRecommendedSongs() {
      const seen = new Set()
      return this.recommendedSongs.filter(song => {
        if (seen.has(song.song_id)) {
          return false
        }
        seen.add(song.song_id)
        return true
      }).slice(0, 3) // 只取前3首
    },
    
    // 去重后的热门歌曲（只显示前3首）
    uniqueHotSongs() {
      const seen = new Set()
      return this.hotSongs.filter(song => {
        if (seen.has(song.song_id)) {
          return false
        }
        seen.add(song.song_id)
        return true
      }).slice(0, 3) // 只取前3首
    }
  },
  
  onLoad() {
    this.initPlayer()
    this.loadData()
  },

  onShow() {
    this.updatePlayerState()
  },

  methods: {
    // 初始化播放器
    initPlayer() {
      musicPlayer.init()
      
      // 监听播放器事件
      musicPlayer.on('play', () => {
        this.isPlaying = true
      })
      
      musicPlayer.on('pause', () => {
        this.isPlaying = false
      })
      
      musicPlayer.on('error', (error) => {
        console.error('播放错误:', error)
        uni.showToast({
          title: '播放失败，请稍后重试',
          icon: 'none'
        })
      })
    },

    // 更新播放器状态
    updatePlayerState() {
      const playerInfo = musicPlayer.getCurrentInfo()
      this.currentSong = playerInfo.song
      this.isPlaying = playerInfo.isPlaying
    },

    // 加载数据
    async loadData() {
      try {
        // 加载轮播图
        const bannersRes = await api.music.getBanners()
        this.banners = bannersRes.data || []

        // 加载推荐歌曲
        const recommendedRes = await api.music.getRecommended()
        this.recommendedSongs = recommendedRes.data || []

        // 加载热门歌曲
        const hotRes = await api.music.getHot()
        this.hotSongs = hotRes.data || []
      } catch (error) {
        console.error('加载数据失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },

    // 搜索
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        uni.showToast({
          title: '请输入搜索关键词',
          icon: 'none'
        })
        return
      }
      
      // 这里可以跳转到搜索结果页面
      uni.navigateTo({
        url: `/pages/search/search?keyword=${encodeURIComponent(this.searchKeyword)}`
      })
    },

    // 轮播图点击
    handleBannerClick(banner) {
      console.log('轮播图点击:', banner)
    },

    // 播放歌曲
    async playSong(song, index) {
      try {
        // 先获取歌曲详情（这会自动记录播放历史）
        const response = await api.music.getSongDetail(song.song_id)
        const songDetail = response.data || song
        
        // 设置播放列表（使用去重后的数据）
        const playlist = [...this.uniqueRecommendedSongs, ...this.uniqueHotSongs]
        musicPlayer.setPlaylist(playlist, playlist.findIndex(s => s.song_id === song.song_id))
        
        // 更新当前歌曲状态
        this.currentSong = songDetail
        this.isPlaying = true
      } catch (error) {
        console.error('播放歌曲失败:', error)
        uni.showToast({
          title: '播放失败，请稍后重试',
          icon: 'none'
        })
      }
    },

    // 切换播放状态
    togglePlay() {
      musicPlayer.togglePlay()
    },

    // 下一首
    nextSong() {
      musicPlayer.next()
    },

    // 跳转到播放器页面
    goToPlayer() {
      uni.navigateTo({
        url: '/pages/player/player'
      })
    },

    // 跳转到更多页面
    goToMore(type) {
      uni.navigateTo({
        url: `/pages/more/more?type=${type}`
      })
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.search-bar {
  margin-bottom: 30rpx;
}

.search-input {
  width: 100%;
  height: 80rpx;
  background-color: white;
  border-radius: 40rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.banner-section {
  margin-bottom: 40rpx;
}

.banner-swiper {
  height: 400rpx;
  border-radius: 20rpx;
  overflow: hidden;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.section {
  background-color: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.section-more {
  font-size: 26rpx;
  color: #ff6b6b;
}

.song-list-vertical {
  display: flex;
  flex-direction: column;
}

.song-item-vertical {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.song-item-vertical:last-child {
  border-bottom: none;
}

.song-cover-vertical {
  width: 100rpx;
  height: 100rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.song-info-vertical {
  flex: 1;
}

.song-name-vertical {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-artist-vertical {
  display: block;
  font-size: 24rpx;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-play-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
  border-radius: 30rpx;
}

.play-icon {
  font-size: 30rpx;
  color: #ff6b6b;
}

.mini-player {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.mini-player-cover {
  width: 80rpx;
  height: 80rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.mini-player-info {
  flex: 1;
}

.mini-player-name {
  display: block;
  font-size: 26rpx;
  color: #333;
  margin-bottom: 5rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.mini-player-artist {
  display: block;
  font-size: 22rpx;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.mini-player-controls {
  display: flex;
  align-items: center;
}

.control-btn {
  font-size: 40rpx;
  margin-left: 20rpx;
  padding: 10rpx;
}
</style>
